package router

import (
	"asy-cache-center/asynet"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strconv"
	"strings"
)

var Center = asynet.NewCenter([]string{})

func InitRouter(port string) {
	r := gin.Default()

	// 添加功能
	r.POST("/addNode", AddNode)
	r.GET("/getNode", GetNode)
	r.POST("/getMap", GetAll)

	// 监听端口8000
	r.Run(port)
}

// 添加节点
func AddNode(c *gin.Context) {
	node := strings.Trim(c.PostForm("nodeUrl"), " ")
	num := strings.Trim(c.PostForm("virtualNode"), " ")

	if node == "" || num == "" { // 返回NotAcceptable
		c.JSON(http.StatusNotAcceptable, gin.H{})
		return
	}
	i, err := strconv.Atoi(num)
	if err != nil {
		c.JSON(http.StatusNotAcceptable, gin.H{})
		log.Panicln("[LOG] error :", err.Error())
		return
	}
	Center.Add(i, node)
	c.JSON(http.StatusOK, gin.H{})
}

// 获取节点
func GetNode(c *gin.Context) {
	key := strings.Trim(c.PostForm("key"), " ")
	if key == "" {
		c.JSON(http.StatusNotAcceptable, gin.H{})
		return
	}
	get := Center.Get(key)
	c.JSON(http.StatusOK, gin.H{
		"msg": get,
	})
}

// 获取节点信息表
func GetAll(c *gin.Context) {
	keys, nodeMap := Center.All()
	c.JSON(http.StatusOK, gin.H{
		"keys": keys,
		"map":  nodeMap,
	})
}
